<template>
    <div class="update-name">
        <van-nav-bar
        title="修改昵称"
        left-text="取消"
        @click-left="$emit('close')"
        right-text="完成"
        @click-right="onUpdate"/>

        <van-field
        v-model.trim="message"
        rows="2"
        autosize
        type="textarea"
        maxlength="12"
        placeholder="请输入昵称"
        show-word-limit />
    </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'

export default {
    name: 'UpadteName',
    model: {
        prop: 'username',
        event: 'updateName'
    },
    props: ['username'],
    data () {
        return {
            message: this.username
        }
    },
    methods: {
        async onUpdate () {
            this.$toast.loading({
                message: '保存中...',
                forbidClick: true, // 禁止背景点击
                duration: 0 // 持续时间
            })
            try {
                const localname = this.message
                if (!localname.length) {
                   return this.$toast('昵称不能为空')
                }
                await updateUserProfile({
                    name: localname
                })
                this.$emit('updateName', localname)
                this.$emit('close')
                this.$toast.success('更新成功')
            } catch (error) {
                this.$toast.fail('更新失败')
            }
        }
    }
}
</script>

<style scoped lang="less">
.update-name {
    .van-field {
        margin: 30px 10px 0;
        margin-right: 50px;
    }
}
</style>
